package com.ace.user.mqtt.processor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ace.user.common.constant.C;
import com.ace.user.module.entity.User;
import com.ace.user.module.entity.UserInfo;
import com.ace.user.module.mapper.UserUserInfoMapper;
import com.ace.user.module.mapper.UserUserMapper;
import com.ace.user.mqtt.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 *  * 遗愿消息处理
 * 
 * @author whl
 *
 * @param <T>
 */
@Component
@Slf4j
public class WillMessageProcessor<T> implements Processor<Map<String, Object>> {

	@Resource
	private UserUserInfoMapper userInfoMapper;
	@Lazy
	@Autowired
	private SendMessage sendMessage;
	@Resource
	private UserUserMapper userMapper;
	@Override
	public boolean isProcessing(Map<String, Object> t) {
		return C.DISCONNECT.equals(String.valueOf(t.get("command")));
	}
	@Override
	public void processing(Map<String, Object> t) {
		log.warn("WillMessageProcessor processing t:{}",t.toString());
		Object userId = t.get("userid");
		Object connectNumber = t.get("connectnumber");
		if (userId == null|| connectNumber==null) {
			log.error("will msg format error: userid or connectnumber is empty.");
			return;
		}
		String userIdStr = String.valueOf(userId);
		String connectNumberStr = String.valueOf(connectNumber);
		if (StringUtils.isEmpty(userIdStr)||StringUtils.isEmpty(connectNumberStr)) {
			log.error("will msg format error: userid or connectnumber is empty.");
			return;
		}
		try {
            //查询用户信息
            User user = userMapper.selectOne(new QueryWrapper<User>()
                    .eq(User.DB_ID, userIdStr));
			UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>()
					.eq(UserInfo.DB_ID,userIdStr)
					.eq(UserInfo.DB_CONNECT_NUM,connectNumberStr));
			if (userInfo != null) {
				if(userInfo.getMqttStatus()!=0) {
					userInfo.setMqttStatus(C.N_0);
					userInfoMapper.updateById(userInfo);
					sendMsg(user, userInfo,"offline");
				}
			}
		} catch (Exception e) {
			log.error("error when user leave uid=" +userIdStr , e);
		}
	}
	public void sendMsg(User user, UserInfo userInfo, String command) {
		Map<String, Object> map = new HashMap<>();
		map.put("command", command);
		map.put("userid", user.getId());
		map.put("name", user.getName());
		map.put("fullname", user.getFullName());
		map.put("type", userInfo.getType());
		map.put("description", user.getDescription());
		map.put("arise-topic", user.getAppId() + "-server");
		sendMessage.send(JSON.toJSONString(map), user.getAppId() + "-server");
	}
}
